package com.itheima.health.controller;

import com.itheima.health.common.MessageConst;
import com.itheima.health.common.RedisConst;
import com.itheima.health.entity.Result;
import com.itheima.health.pojo.*;
import com.itheima.health.service.MemberService;
import com.itheima.health.service.OrderService;
import com.itheima.health.service.OrderSettingService;
import com.itheima.health.service.SetMealService;
import com.itheima.health.vo.OrderSubmitParam;
import io.swagger.annotations.Api;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 预约控制器
 */
@RestController
@RequestMapping("/mobile/order")
@Slf4j
@Api(tags = "手机端订单接口")
public class MobileOrderController {

    @Autowired
    private MemberService memberService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderSettingService orderSettingService;

    @Transactional//事务注解
    @PostMapping("/submit")
    //这里没有对应的实体类来接收前端的数据所以用Map来接收,也可以自己写一个实体类
    public Result submit(@RequestBody OrderSubmitParam orderParam) {
        //从前端给到的数据中拿出手机号和验证码
        String validateCode = orderParam.getValidateCode();
        log.info("前端的验证码为:{}",validateCode);
        String phone = orderParam.getTelephone();
        //根据手机号去redis中找存储的生成验证码
        String key =RedisConst.VALIDATE_CODE_PREFIX+"ORDER_"+phone;
        Object redisCode = redisTemplate.opsForValue().get(key);
        log.info("从redis中拿到了验证码+{}",redisCode);
        //首先判断前端传入的数据中是否有预约时间
        Date orderDate = orderParam.getOrderDate();
        log.info("预约时间为:{}",orderDate);
        if(orderDate != null){ //如果没有直接返回false表示添加预约信息失败
            //判断拿到的验证码和生成的验证码是否一样
            if (redisCode != null && redisCode.equals(validateCode)) {
                //如果拿到了验证码则验证码失去作用,删除即可
                redisTemplate.delete(key);
                log.info("验证码已删除");
                //而后根据前端的数据去查询是否是会员
                Member member = memberService.selectPhoneNumber(phone);
                if (member == null) {//判断为空则需要新建会员信息
                    Member newMember = new Member();
                    newMember.setPhoneNumber(phone);
                    newMember.setName(orderParam.getName());
                    newMember.setSex(orderParam.getSex());
                    newMember.setIdCard(orderParam.getIdCard());
                    //将LocalDateTime转换为Date
                    newMember.setRegTime(Date.from(LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant()));
                    memberService.addMember(newMember);
                    log.info("新建会员成功");
                }
                log.info("该手机号为老会员");

                //查询该日期的预约设置信息表单数据
                OrderSetting orderSetting = orderSettingService.selectIdTotal(orderDate);
                log.info("拿到预约表单");
                if(orderSetting != null){
                    //查询该日期的可预约人数是多少
                    int number = orderSetting.getNumber();
                    log.info("可预约的人数:{}",number);
                    //拿到该日期已预约人数
                    int idTotal = orderSetting.getReservations();
                    //查询预约人数是否已满
                    if (number > idTotal) {
                        log.info("预约人数未满");
                        //查看当前手机号对应的会员信息表单(由于可能是新建用户所以重新查询)
                        Member member1 = memberService.selectPhoneNumber(phone);
                        //从查询到的会员信息表单中拿到主键id,调用order中的方法根据会员id查询预约信息
                        Order order = orderService.selectMemberId(member1.getId());
                        //判断该账号是否预约过
                        if (order != null) {
                            log.info("当前用户已在当天预约");
                            return new Result(false, "当前用户已在当天预约");
                        }
                        log.info("可以预约");
                        //调用Service中的添加预约信息的方法
                        //补充order表中的数据信息
                        Order order1 = new Order();
                        log.info("新建order完成,准备储存数据");
                        String string = member1.getId().toString();
                        log.info("会员id存储中:ID{}", string);
                        order1.setMemberId(Integer.parseInt(string));
                        log.info("会员id存储完成:ID{}", order1.getMemberId());
                        order1.setOrderDate(orderParam.getOrderDate());
                        order1.setOrderStatus("未到诊");
                        order1.setSetmealId(orderParam.getSetMealId());
                        order1.setOrderType("电话预约");
                        log.info("预约信息准备存储");
                        orderService.addOrder(order1);
                        log.info("预约信息存储完成");
                        //添加当天已完成预约人数
                        orderSetting.setReservations(idTotal + 1);
                        orderSettingService.increaseReservations(orderSetting);
                        log.info("预约成功");

                        return new Result(true,"预约成功", order1);
                    } else {
                        return new Result(false, "预约人数已满");
                    }
                }
                return new Result(false,"当天不可进行预约");
            }
            return new Result(false,"短信验证码不正确");
        }
        return new Result(false,"预约时间不得为空");
    }

    //预约成功页面
    @GetMapping("/findById")
    public Result findById(Integer id){

       //通过订单id去查 四个信息
        OrderInfo orderInfo = orderService.selectSetmealAndMemberByOrderId(id);

        return new Result(true,MessageConst.GET_ORDERSETTING_SUCCESS,orderInfo);


    }






}
